package com.kstech.ks_gaz01.test

import com.blankii.androidlibrary.base.BaseBindingActivity
import com.blankii.androidlibrary.utils.CRC16Util
import com.easysocket.EasySocket
import com.easysocket.config.EasySocketOptions
import com.easysocket.entity.OriginReadData
import com.easysocket.entity.SocketAddress
import com.easysocket.interfaces.conn.SocketActionListener
import com.easysocket.utils.LogUtil
import com.kstech.ks_gaz01.databinding.ActivityTestBinding



//https://github.com/jiusetian/EasySocket
class TestActivity : BaseBindingActivity<ActivityTestBinding>(ActivityTestBinding::inflate) {
    private val stringBuider = StringBuilder()
    private var IP: String = "10.10.100.102"
    private var PORT: Int = 8080
    override fun onInitView() {
        //连接socket
        binding.submit.setOnClickListener {
            IP = if (binding.ip.text.toString().isNotEmpty()) binding.ip.text.toString() else IP
            PORT = if (binding.port.text.toString().isNotEmpty()) binding.port.text.toString()
                .toInt() else PORT
            LogUtil.d("IP:${IP},端口:${PORT}");
            initEasySocket(IP, PORT)
        }
        //发送消息
        binding.sendMsg.setOnClickListener {
            stringBuider.append("已发送->${binding.hexMsg.text.toString()}")
            sendMessage(binding.hexMsg.text.toString())
            showView()
        }
        //生成校验码
        binding.createCRC16.setOnClickListener {
            val crc16: String = CRC16Util.getCRC(Hex2Byte(binding.hexMsg.text.toString()))
            binding.hexMsg.append(processCRC16(crc16))
        }
    }

    override fun onInitData() {

    }

    private fun processCRC16(crc16: String): String {
        return " " + crc16.substring(2) + " " + crc16.substring(0, 2)
    }


    private val socketActionListener = object : SocketActionListener() {
        override fun onSocketConnSuccess(socketAddress: SocketAddress?) {
            super.onSocketConnSuccess(socketAddress)
            LogUtil.d("连接成功");
        }

        override fun onSocketConnFail(socketAddress: SocketAddress?, isNeedReconnect: Boolean) {
            super.onSocketConnFail(socketAddress, isNeedReconnect)
            LogUtil.d("连接失败");
        }

        override fun onSocketDisconnect(socketAddress: SocketAddress?, isNeedReconnect: Boolean) {
            super.onSocketDisconnect(socketAddress, isNeedReconnect)
            LogUtil.d("断开连接");
        }

        override fun onSocketResponse(
            socketAddress: SocketAddress?,
            originReadData: OriginReadData?
        ) {
            super.onSocketResponse(socketAddress, originReadData)
            stringBuider.append("已接收->${Byte2Hex(originReadData!!.originDataBytes)}")
            showView()
        }

    }

    private fun showView() {
        binding.receiveMsg.text = stringBuider.toString()
    }

    /**
     * 发送一个的消息，
     */
    private fun sendMessage(hex: String) {
        //发送
        EasySocket.getInstance()!!.upMessage(Hex2Byte(hex))
    }

    /**
     * 初始化EasySocket
     */
    private fun initEasySocket(ip: String, port: Int) {
        //socket配置
        val options = EasySocketOptions.Builder()
            .setSocketAddress(SocketAddress(ip, port)) //主机地址
            // 强烈建议定义一个消息协议，方便解决 socket黏包、分包的问题
//            .setReaderProtocol(DefaultMessageProtocol()) // 默认的消息协议
            .build()

        //初始化EasySocket
        EasySocket.getInstance().createConnection(options, this)
        //监听socket相关行为
        EasySocket.getInstance().subscribeSocketAction(socketActionListener);
    }

    //16进制字符串转byte数组
    fun Hex2Byte(inHex: String): ByteArray? {
        val hex = inHex.split(" ".toRegex()).toTypedArray() //将接收的字符串按空格分割成数组
        val byteArray = ByteArray(hex.size)
        for (i in hex.indices) {
            //parseInt()方法用于将字符串参数作为有符号的n进制整数进行解析
            byteArray[i] = hex[i].toInt(16).toByte()
        }
        return byteArray
    }

    //byte数组转16进制字符串
    fun Byte2Hex(inByte: ByteArray): String? {
        val sb = StringBuilder()
        for (b in inByte) {
            sb.append(String.format("%02x", b) + "\t")
        }
        return sb.toString().uppercase()
    }
}